<template>
  <div class="container">

    <sq-header :selected="1"></sq-header>

    <div class="swiper-list">
      <mt-swipe :auto="2000" :continuous="true">
         <template v-for="(item, index) in recommondItems">
          <mt-swipe-item>
            <div class="swipe-box">
              <img v-bind:src="item.imgUrl" alt="" @click="goToRecommend(item.targetUrl)">
            </div>
          </mt-swipe-item>
        </template>
      </mt-swipe>
    </div>

    <ul class="course-list"
        v-if="shouldUseScroll"
        v-infinite-scroll="loadMore"
        infinite-scroll-disabled="loading"
        infinite-scroll-distance="100">
    	    <sq-course-item v-for="(item, index) in indexItems" :item="item" :key="item.id" @clickCourse="goToCourseDetail(item)"></sq-course-item>
    </ul>

    <mt-loadmore :bottom-method="loadMore" :bottom-all-loaded="false"
                 :bottomPullText="bottomPullText" :bottomDropText="bottomDropText" ref="loadmore" v-if="!shouldUseScroll">
      <ul class="course-list">
        <sq-course-item v-for="(item, index) in indexItems" :item="item" :key="item.id" @clickCourse="goToCourseDetail(item)"></sq-course-item>
      </ul>
    </mt-loadmore>

    <sq-goto-top-button></sq-goto-top-button>

  </div>
</template>

<script>
import Vue from 'vue'
import {mapGetters } from 'vuex';
import {Swipe, SwipeItem, InfiniteScroll, Loadmore } from 'mint-ui'
import SqHeader from '../components/Header'
import SqIndexCourse from '../components/CourseItem'
import GotoTopButton from '../components/GotoTopButton'

Vue.component(Swipe.name, Swipe)
Vue.component(SwipeItem.name, SwipeItem)
Vue.component(SqHeader.name, SqHeader)
Vue.component(SqIndexCourse.name, SqIndexCourse)
Vue.component(GotoTopButton.name, GotoTopButton)
Vue.component(Loadmore.name, Loadmore);
Vue.use(InfiniteScroll);
Vue.use(Loadmore);
import {getRecommendCourse, getIndexCourse} from '../api/index'

const LIMIT = 10;

const MAX_LOAD_MORE_COUNT = 100;

// android chrome 机制问题，认为touch阻塞了scoll事件，对touch事件做了限制
// https://bugs.chromium.org/p/chromium/issues/detail?id=260732
// 所以针对android chrome 采用滚动加载的方式
// firefox 也有同样的问题
var shouldUseScroll = function() {
  var ua = window.navigator.userAgent;
  if (/Firefox\//.test(ua)) {
    return true;
  }
  if (/AppleWebKit\/[.0-9]* \(KHTML, like Gecko\) Chrome\/[.0-9]* Mobile Safari\/[.0-9]*$/.test(ua)) {
    return true;
  }
  // 其它浏览器用 拖动的方式
  return false;
}

export default {
  name: 'Index',
  data () {
    return {
      recommondItems: [],
      indexItems: [],
      loading: false,
      allLoaded: false,
      shouldUseScroll: shouldUseScroll(),
      bottomPullText: '上拉刷新',
      bottomDropText: '释放更新',
      loadMoreCount: 0,
    }
  },
  created () {
      var that = this;
      getRecommendCourse().then(function(resp){
        that.recommondItems = resp.data;
      }).catch(function(err){
        console.log(err);
      });
      this.loadMore();
  },
  destroyed() {
    document.getElementById("app").style.paddingBottom = '0px';
  },
  computed: {
    ...mapGetters([
      'channel',
      'showListenBar'
    ])
  },
  methods: {
    goToCourseDetail(item) {
      this.$router.push({ name: 'Course', params: { id: item.id, randId: item.randId } });
    },
    goToRecommend(targetUrl) {
      var reg = /\/(course|category)\/(\d*)\/(.*)$/
      if(reg.test(targetUrl)){
        var type = RegExp.$1;
        var targetId = RegExp.$2;
        var randId = RegExp.$3;
        if(type == "course"){
          this.$router.push({ name: 'Course', params: { id: targetId, randId: randId } });
        }else if(type == "category"){
          this.$router.push({ name: 'Category', params: { id: targetId, randId: randId } });
        }
      }
    },
    loadMore() {
      // console.log("loadMore before");
      // 1、不允许并发加载
      // 2、总次数限制，防止bug导致无限加载，耗费用户流量
      // 3、所有都加载完了，也不让加载更多了
      if(this.loading || this.loadMoreCount > MAX_LOAD_MORE_COUNT) {
        return;
      }
      this.loading = true;
      this.loadMoreCount += 1;
      var offset = this.indexItems.length;
      var that = this;
      getIndexCourse(offset, LIMIT).then(function(resp){
        if(resp.data && resp.data.length > 0){
          //防止并发请求，重复添加数据
          if(offset === that.indexItems.length){
            that.indexItems = that.indexItems.concat(resp.data);
          }
          that.allLoaded = false;
        } else {
          that.allLoaded = true;
          that.bottomPullText = '没有更多了';
          that.bottomDropText = '没有更多了';
        }
        that.loading = false;
        if(that.$refs.loadmore) {
          that.$refs.loadmore.onBottomLoaded();
          // loadMore组件会导致出现滚动条（头部header被滑动了), 原因暂时不清楚
          // 添加下面的逻辑，loadMore加载以后，判断头部header是否被滑动了，是的话就自动scroll到顶部
          //if(that.$store.getters.showListenBar){
          //  return;
          //}
          that.$nextTick(function () {
              if(that.$store.getters.showListenBar){
                document.getElementById("app").style.paddingBottom = '44px';
              }
              const HEADER_HEIGHT = 51;
              // scroll to top
              if (window.document.body.scrollTop <= HEADER_HEIGHT) {
                window.document.body.scrollTop = 0;
              }
              if (window.document.documentElement.scrollTop <= HEADER_HEIGHT) {
                window.document.documentElement.scrollTop = 0;
              }
          })
        } else {
          that.$nextTick(function () {
            if (that.$store.getters.showListenBar) {
              document.getElementById("app").style.paddingBottom = '44px';
            }
          })
        }
      }).catch(function(err){
        console.log(err);
        that.$refs.loadmore && that.$refs.loadmore.onBottomLoaded();
      });
    }
  }
}
</script>

<style scoped>

  .container{
  	width: 100%;
  	margin: 0px;
  	padding: 0px;
  }

  .swiper-list {
  	width: 100%;
  	height: 200px;
    height: 40vw;
  }

  @media screen and (min-width: 769px) {
      .swiper-list {
        height: 200px;
      }
  }

  .swipe-box img {
  	width:100%;
  	height:100%;
  }

  .course-list {
    padding: 0px;
    margin: 0px;
  }

</style>
